package com.handa.common.feign;

import com.handa.common.config.SnowflakeConfig;
import com.handa.common.entity.LoginUser;
import com.handa.common.security.MyTokenService;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


@Component
public class FeignInterceptor implements RequestInterceptor {

    @Resource
    private MyTokenService myTokenService;

    @Resource
    private SnowflakeConfig snowflakeConfig;


    @Value("${spring.application.name:unknown}")
    private String appName;


    @Override
    public void apply(RequestTemplate requestTemplate) {
        String requestId = null;
        String authorization = null;

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            requestId = request.getHeader("requestId");
            authorization = request.getHeader("Authorization");
        }

        if (StringUtils.isBlank(requestId)) {
            requestId = requestId();
        }

        if (StringUtils.isBlank(authorization)) {
            authorization = generateDefaultToken();
        }

        requestTemplate.header("requestId", requestId);
        requestTemplate.header("Authorization", authorization);
    }

    private String requestId() {
        return "#" + snowflakeConfig.snowflakeId();
    }

    private String generateDefaultToken() {
        LoginUser appUser = new LoginUser();
        appUser.setUserId(-1L);
        appUser.setNickname("微服务内部调用");
        appUser.setUsername(appName);
        appUser.setRoleId(0);
        return myTokenService.newToken(appUser);
    }
}
